<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>深度克隆</title>
</head>
<body>
    


    <script>


        // 对象的深度拷贝

        /* function deepCopy (obj) {
            var buf;
            if (obj instanceof Array) {
                buf = [];
                var i = obj.length;
                while (i--) {
                    buf[i] = obj[i];
                }
            }else if (obj instanceof Object) {
                buf = {};
                for (const key in obj) {
                    if (obj.hasOwnProperty(key)) {
                        const element = obj[key];
                        buf[key] = element;
                    }
                }
                return buf;
            }else {
                return obj;
            }
        } */


       function deepCopy (target) {
            
           let buf;

           if(target instanceof Array){
                buf = [];
                for (let i=0;i<target.length;i++) {
                    buf.push(target[i]);
                }

                return buf;
           } else if (target instanceof Object) {

                buf = {};
                for (const key in target) {
                    if (target.hasOwnProperty(key)) {
                        const element = target[key];
                        buf[key] = element;
                    }
                }
                return buf;

           } else {

                return target;

           }
       }

       console.log(deepCopy([1,2,3,4,5]));
       console.log(deepCopy({name: 'ws',age: 20}));


       

    


    
        
    </script>
</body>
</html>